package com.example.a15787.weather_zyy_1235;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CitySearchActivity extends AppCompatActivity implements FavoritesAdapter.OnStartDragListener {
    private EditText etCitySearch;
    private Button btnSearch;
    private TextView tvSearchResult;
    private BottomNavigationView bottomNavigationView;
    private List<String> cityNames = new ArrayList<>();
    private WeatherResponse weatherResponse;
    private List<String> favorites = new ArrayList<>();
    private RecyclerView rvFavorites;
    private FavoritesAdapter favoritesAdapter;
    private boolean isBatchDeleteMode = false;
    private ItemTouchHelper itemTouchHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_search);

        etCitySearch = findViewById(R.id.etCitySearch);
        btnSearch = findViewById(R.id.btnSearch);
        tvSearchResult = findViewById(R.id.tvSearchResult);
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        rvFavorites = findViewById(R.id.rvFavorites);

        loadFavorites();

        rvFavorites.setLayoutManager(new LinearLayoutManager(this));
        favoritesAdapter = new FavoritesAdapter(favorites, this, this);
        rvFavorites.setAdapter(favoritesAdapter);

        setupItemTouchHelper();

        new WeatherTask().execute("http://192.168.0.108:8080/weather-api/new_weather_data.json");

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String cityName = etCitySearch.getText().toString().trim();
                if (cityName.isEmpty()) {
                    Toast.makeText(CitySearchActivity.this, "请输入城市名称", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (cityNames.contains(cityName)) {
                    if (!favorites.contains(cityName)) {
                        favoritesAdapter.addItem(cityName);
                    }
                    selectFavoriteCity(cityName);
                } else {
                    Toast.makeText(CitySearchActivity.this, "无法搜索到该城市", Toast.LENGTH_SHORT).show();
                }
            }
        });

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_back:
                        Intent intent = new Intent(CitySearchActivity.this, MainActivity.class);
                        intent.putExtra("SELECT_WEATHER_TAB", true);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                        return true;
                }
                return false;
            }
        });
    }

    private void setupItemTouchHelper() {
        ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                return makeMovementFlags(dragFlags, 0);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                                  RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                favoritesAdapter.moveItem(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
            }
        };

        itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(rvFavorites);
    }

    @Override
    public void onStartDrag(RecyclerView.ViewHolder viewHolder) {
        itemTouchHelper.startDrag(viewHolder);
    }

    public void selectFavoriteCity(String cityName) {
        Intent intent = new Intent(CitySearchActivity.this, MainActivity.class);
        intent.putExtra("SELECTED_CITY", cityName);
        intent.putExtra("SELECT_WEATHER_TAB", true);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.city_search_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_delete_all:
                if (favoritesAdapter.isEditMode()) {
                    deleteSelectedItems();
                } else {
                    favoritesAdapter.setEditMode(true);
                    item.setTitle("完成");
                }
                return true;
            case R.id.action_edit_mode:
                if (favoritesAdapter.isEditMode()) {
                    favoritesAdapter.setEditMode(false);
                    item.setTitle("编辑");
                } else {
                    favoritesAdapter.setEditMode(true);
                    item.setTitle("取消");
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void deleteSelectedItems() {
        if (favorites.isEmpty()) {
            Toast.makeText(this, "没有可删除的城市", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除所有收藏的城市吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        favorites.clear();
                        favoritesAdapter.notifyDataSetChanged();
                        saveFavorites();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void loadFavorites() {
        SharedPreferences prefs = getSharedPreferences("CityPrefs", MODE_PRIVATE);
        String json = prefs.getString("favorites", null);
        if (json != null) {
            try {
                JSONArray jsonArray = new JSONArray(json);
                favorites = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    favorites.add(jsonArray.getString(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                favorites = new ArrayList<>();
            }
        } else {
            favorites = new ArrayList<>();
        }
    }

    public void saveFavorites() {
        SharedPreferences prefs = getSharedPreferences("CityPrefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        JSONArray jsonArray = new JSONArray(favorites);
        editor.putString("favorites", jsonArray.toString());
        editor.apply();
    }

    private class WeatherTask extends AsyncTask<String, Void, WeatherResponse> {
        @Override
        protected WeatherResponse doInBackground(String... urls) {
            try {
                String jsonResponse = NetworkUtils.fetchWeatherData(urls[0]);
                return WeatherParser.parse(jsonResponse);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(WeatherResponse result) {
            if (result != null) {
                weatherResponse = result;
                setupCityNames();
            }
        }
    }

    private void setupCityNames() {
        cityNames.clear();
        for (WeatherResponse.City city : weatherResponse.cities) {
            cityNames.add(city.getCityName());
        }
    }
}